package com.niit.agricstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.niit.agricstore.entity.Comment;
import com.niit.agricstore.mapper.CommentMapper;
import com.niit.agricstore.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    CommentMapper commentMapper;
    @Override
    public PageInfo<Comment> getAllComments(int pageNum, int pageSize) {
        Page<Comment> page = new Page<>(pageNum, pageSize);
        page = commentMapper.selectPage(page, null);
        List<Comment> commentList = page.getRecords();
        return PageInfo.of(commentList);
    }

        @Override
        public PageInfo<Comment> getCommentByUserId( Long commentUserId, int pageNum, int pageSize) {
            Page<Comment> page = new Page<>(pageNum, pageSize);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.likeRight("comment_user_id",commentUserId);
            page = commentMapper.selectPage(page, queryWrapper);
            List<Comment> commentList = page.getRecords();
            return PageInfo.of(commentList);
        }

    @Override
        public String createComment(Comment comment) {
        if (comment.getCommentContent() != null ) {
            // 保存评论的逻辑
            if(commentMapper.insert(comment)>0) return "发送成功";
            else return "发送失败请重试";
        }
        return "发送失败！评论不能为空";
        }

        @Override
        public int deleteCommentById(int commentId) {
            return commentMapper.deleteById(commentId);
        }

        @Override
        public int markCommentAsRead(int commentId, int isRead) {
            Comment comment = commentMapper.selectById(commentId);
            comment.setCommentIsRead(isRead);
            return commentMapper.updateById(comment);
        }

        @Override
        public int markCommentBatchAsRead() {
            return commentMapper.updateAllCommentRead();
        }

        @Override
        public int markCommentAsReplied(int  commentId, int isReplied) {
            Comment comment = commentMapper.selectById(commentId);
            comment.setCommentIsReply(isReplied);
            return commentMapper.updateById(comment);
        }
    }

